
import React, { Component, useState  } from "react";
import { Select } from 'antd';
import message from "components/Mes";
import "sass/userInfo/MyManage.scss";
import {cityData} from 'utils/city.js';
import { afcExport, b6De, phoneReg} from 'utils/base.js';
import Cookies from "js-cookie";
import http from "service/members";
const { Option } = Select;
export default class MyManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cityData: cityData,
      industry: '请选择行业',
      companyLogoUrl: '',
      companyName: '',
      contacts: '',
      province:'',
      phone: '',
      position: '',
      city: '',
      mainProducts: '',
      companyIntroduction: '',
      Industrys:[], // 会员信息
      cities:[],
      userInfo:{},
      memberInfo:{},
      submitStatus:false,
      checkInputValStatus:true
    };
  }
  async componentDidMount () {
    let Industrys= await http.getIndustry()
    console.log(Industrys,23)
    let cook = Cookies.get("useInfo");
    if (!cook) {
      window.location.href ='#/user/login'
    }
    let obj = b6De(cook);
    this.setState({
      Industrys: Industrys,
      userInfo: obj
    });
    this.queryMemberInfo()
  }

  componentWillUnmount () {
  }
  queryMemberInfo = async () => {
    let { userInfo} =this.state
    let memberInfo = await http.getMemberInfo({
      userId: userInfo.userId
    })
    if (memberInfo.list){
      this.setState((prevState) => ({
        memberInfo: memberInfo.list,
        industry: memberInfo.list.industry,
        companyLogoUrl: memberInfo.list.companyLogoUrl,
        companyName: memberInfo.list.companyName,
        contacts: memberInfo.list.contacts,
        province: memberInfo.list.province,
        phone: memberInfo.list.phone,
        position: memberInfo.list.position,
        city: memberInfo.list.city,
        mainProducts: memberInfo.list.mainProducts,
        companyIntroduction: memberInfo.list.companyIntroduction
      }))
      console.log(this.state,3434);
      
    }
  }
  getVal=(type,e)=>{
    let val = e.target.value
    this.setState({
      [type]: val
    });
    // setTimeout(() => {
    //   if (val === '') {
    //     message("warning", "请输入内容");
    //   } else if ((type == 'companyName' || type == 'contacts' || type == 'position' || type == 'mainProducts' || type == 'companyIntroduction') && !afcExport.test(val)) {
    //     message("warning", "请输入中英文格式内容");
    //   } else if (type == 'phone' && !phoneReg.test(val)) {
    //     message("warning", "请输入正确的手机格式");
    //   }
    // }, 100);
  }
 
  changeSelect=(type,val)=>{
    
    if (type =='province') {
      this.setState((prevState) => ({
        province:val,
        cities: this.state.cityData[val],
        city:'',
      }))
    }
    this.setState((prevState) => ({
      [type]: val
    }));
    
    setTimeout(() => {
      console.log(this.state, type, val, 3434);
    }, 0);
  }
  mapCitys=(name)=>{
    if (name=='1'){
      let cities = this.state.cityData[0].cities
      this.setState({
        cities: cities
      });
    }
  }
  changeImg = async(e) =>{
    let file = e.target.files[0]
    let reader = new FileReader()
    let formData = new FormData();
    if (file.size >= 1024 * 1024 *2) {
      message("warning", "所选图片不能大于2MB");
      return;
    };
    reader.readAsDataURL(file);
    formData.append("file", file);
    let img = await http.updateImg(formData)
    this.setState({
      companyLogoUrl: img
    })
  }
  submitInfo=async (e)=>{
    e.preventDefault()
    if (this.state.submitStatus){
      return
    }
    this.setState({ submitStatus: true})
    message("loading", "Loading...");
    let { userInfo, memberInfo, industry, province,companyName, companyLogoUrl, contacts,phone, position, city, mainProducts, companyIntroduction} = this.state
  
    
    let formDatas={
      userId: userInfo.userId,
      industry, 
      companyLogoUrl,
      companyName,
      contacts, 
      phone,
      position, 
      city,
      province,
      mainProducts,
      companyIntroduction
    }
    if (memberInfo.memberId) {
      formDatas.memberId = memberInfo.memberId
    }
    if (this.checkNull()) {
      this.setState({ submitStatus: false })
      let res = await http.addEditMember(formDatas)
      if (res.success) {
        message('success', res.message);
        this.setState({ submitStatus: false })
        setTimeout(() => {
          window.location.reload()
        }, 100);
      }
    }else{
      this.setState({ submitStatus: false })
    }
  }
  checkNull(){
    let checkInputValStatus = true
    let errText={
      industry:'请选择行业',
      companyLogoUrl:'请上传企业LOGO',
      companyName:'请输入企业名称', 
      contacts:'请输入联系人', 
      phone:"请输入联系人电话",
      position:'请输入职位',
      province: '请选择省份',
      city:'请选择城市', 
      mainProducts:"请输入主营产品",
      companyIntroduction:"请输入公司简介"
    }
    for (const key in errText) {
      if (this.state[key] == '' || this.state[key] =='请选择行业') {
        message("warning", errText[key]);
        checkInputValStatus = false
        break
      } else if ((key == 'companyName' || key == 'contacts' || key == 'position' || key == 'mainProducts' || key == 'companyIntroduction') && !afcExport.test(this.state[key])) {
        message("warning", "请输入中英文格式内容");
        break
      } else if (key == 'phone' && !phoneReg.test(this.state[key])) {
        message("warning", "请输入正确的手机格式");
        break
      }
    }
    return checkInputValStatus
  }
  toUserHome =(e) =>{
    e.preventDefault()
    window.location.href='#/userInfo'
  }
  render () {
    let { cityData, Industrys, cities, province, companyLogoUrl} = this.state
    return (
      <div className="myspace clearfix">
          <div className="my-manage">
            <div className="header">
              <h3 className="title">个人信息</h3>
              <h4 className="subtitle">会员信息管理</h4>
            </div>
            <form method="POST" className="manage-form">
              <ul className="form-list">
                <li>
                  <label>请选择行业：</label>
                    <Select value={this.state.industry} onChange={this.changeSelect.bind(this, 'industry')} style={{ width: 336, height: 50 }}>
                      {!!Industrys.length && Industrys.map((item) => {
                        return (<Option key={item.categoryId} value={item.categoryName} >{item.categoryName}</Option>)
                      })}
                    </Select>
                </li>
                <li>
                  <label>请上传企业LOGO：</label>
                  <div className="right">
                    {companyLogoUrl != '' && (<div className="add-file">
                      <img src={`http://yjw-image.oss-cn-shenzhen.aliyuncs.com/${companyLogoUrl}`} alt=""/>
                      <input type="file" accept="image/jpeg,image/jpg,image/png" onChange={this.changeImg} />
                    </div>)
                    }
                    {companyLogoUrl == ''&&(<div className="add-file">
                      <i></i>
                      <input type="file" accept="image/jpeg,image/jpg,image/png" onChange={this.changeImg}/>
                    </div>)
                    }
                    
                    <p className="tip">支持jpg,jpeg,png格式图片上传</p>
                  </div>
                </li>
                <li>
                  <label>请输入企业名称：</label>
                  <div className="right">
                  <input type="text" placeholder="请输入企业名称" value={this.state.companyName} onChange={this.getVal.bind(this,'companyName')} maxLength="30" />
                  </div>
                </li>
                <li>
                  <label>请输入联系人：</label>
                  <div className="right">
                  <input type="text" placeholder="请输入联系人" value={this.state.contacts} onChange={this.getVal.bind(this, 'contacts')}  maxLength="15"/>
                  </div>
                </li>
                <li>
                  <label>请输入联系人电话：</label>
                  <div className="right">
                  <input type="text" placeholder="请输入联系人电话" value={this.state.phone} onChange={this.getVal.bind(this, 'phone')} maxLength="15"/>
                  </div>
                </li>
                  <li>
                    <label>请输入职位：</label>
                    <div className="right">
                  <input type="text" placeholder="请输入职位" value={this.state.position} onChange={this.getVal.bind(this, 'position')} maxLength="20"/>
                    </div>
                  </li>
                  <li>
                    <label>请选择所在城市：</label>
                   <Select  
                  value={this.state.province}
                    onChange={this.changeSelect.bind(this,'province')} 
                    style={{ width: 160, height: 50 }}>
                      {!!Object.keys(cityData).length&& Object.keys(cityData).map((item) => {
                        return (<Option key={item} value={item} >{item}</Option>)
                      })}
                    </Select>
                    {
                    province && (
                    <Select
                      value={this.state.city}
                        onChange={this.changeSelect.bind(this, 'city')}
                        style={{ width: 160, height: 50, marginLeft: 16 }}>
                        {!!cities.length && cities.map((item) => {
                          return (<Option key={item} value={item.label} >{item.label}</Option>)
                        })}
                      </Select>
                      )
                    }
                  </li>
                  <li>
                    <label>请输入主营产品：</label>
                    <div className="right">
                  <textarea name="product" id="product" maxLength="500" value={this.state.mainProducts} onChange={this.getVal.bind(this, 'mainProducts')} placeholder="请输入主营产品"></textarea>
                    </div>
                  </li>
                  <li>
                    <label>请输入公司简介：</label>
                    <div className="right">
                  <textarea name="introduction" maxLength="500" value={this.state.companyIntroduction} id="introduction" onChange={this.getVal.bind(this, 'companyIntroduction')} placeholder="请输入公司简介"></textarea>
                    </div>
                  </li>
                  <li>
                    <label></label>
                    <div className="right">
                      <button className="submit" onClick={this.submitInfo.bind(this)}>提交</button>
                      <button className="cancel" onClick={this.toUserHome.bind(this)}>取消</button>
                    </div>
                  </li>
                </ul>
              </form>
          </div>
      </div>
    );
  }
}
